package com.stu.wgt.test.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.stu.wgt.test.bean.ShoppingCart;
import com.stu.wgt.test.mapper.ShoppingCartMapper;
import com.stu.wgt.test.result.R;
import com.stu.wgt.test.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author wgt
 * @since 2024-02-04
 */
@RestController
@RequestMapping("/shopping-cart")
public class ShoppingCartController {

    @Autowired
    ShoppingCartService service;

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public R addShoppCart(@RequestBody ShoppingCart shoppingCart) {
        try {
            System.out.println(shoppingCart);
            int result = service.insert(shoppingCart);
            if (result == 1) {
                return R.ok().data("msg", "添加成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.error().data("msg", "添加失败");
    }

    // 批量删除数据
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public R deleteShoppCart(@RequestBody List<Integer> ids) {
        try {
            for (Integer id : ids) {
                service.delete(id);
            }
            return R.ok().data("msg", "删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return R.error().data("msg", "删除失败");
        }
    }

    @RequestMapping(value = "/update/{id}", method = RequestMethod.PUT)
    public R updateShoppCart(@PathVariable("id") Integer id, @RequestBody ShoppingCart shoppingCart) {
        shoppingCart.setId(id);
        int result = service.insert(shoppingCart);
        if (result == 1) {
            return R.ok().data("msg", "更新成功");
        }
        return R.error().data("msg", "更新失败");
    }

    @RequestMapping(value = "/selectById/{id}", method = RequestMethod.GET)
    public R selectById(@PathVariable("id") Integer id) {
        try {
            List<ShoppingCart> shoppingCartList = service.selectById(id);
            return R.ok().data("shoppcart", shoppingCartList);
        } catch (Exception e) {
            return R.error().data("msg", "查询失败");
        }
    }

    @RequestMapping(value = "/search", method = RequestMethod.GET)
    public R searchShoppCart(
            @RequestParam("userId") Integer userId,
            @RequestParam("pagenum") Integer pageNum,
            @RequestParam("pagesize") Integer pageSize
    ) {
        try {
            IPage<ShoppingCart> shoppingCartIPage = service.searchShoppingCart(userId, pageNum, pageSize);
            return R.ok().data("shoppcart", shoppingCartIPage.getRecords()).data("total", shoppingCartIPage.getTotal());
        } catch (Exception e) {
            return R.error().data("msg", "查询失败");
        }
    }

}

